/// <reference path="../../index.d.ts" />
const Service = require("egg").Service
class Db extends Service {
	constructor(ctx) {
		super(ctx)
		this.serverConfig = this.config.serverConfig
	}
	async getRedisObj(key) {
		let str = await this.app.redis.get(key)
		if (!str) {
			return undefined
		}
		try {
			let obj = JSON.parse(str)
			if (obj instanceof Object)
				return obj
			throw new Error("错误类型")
		} catch (error) {
			this.ctx.logger.error("redis:" + key)
			return undefined
		}
	}
	/**
	 * deal 返回fale 可以阻止写进redis
	 * 没有deal 直接返回结果/ 并写入redis
	 * 时间为s 单位
	 * @template T
	 * @param {string} key 
	 * @param {{noExist:function():Promise<T>,deal?:function(val:T):Promise<T>,expire?:Number}} action 
	 * @returns {{stat:boolean,data:T}}
	 */
	async getSet(key, action) {
		let obj = await this.getRedisObj(key)
		let hasChange = false
		if (!obj) {
			// 初始化
			obj = await action.noExist()
			hasChange = true
			if (!obj) {
				return {stat: false}
			}
		}
		if (action.deal) {
			obj = await action.deal(obj)
			hasChange = true
		}
		if (!(obj instanceof Object)) {
			return {stat: false}
		}
		if (hasChange) {
			await this.app.redis.set(key, JSON.stringify(obj), "ex", Math.floor(action.expire || -1))
		}
		return {stat: true, data: obj}
	}
}
module.exports = Db